package cn.four.hqServer.modules.userlogin.controller;

import cn.four.hqServer.common.entity.HqUserInfo;
import cn.four.hqServer.common.result.Result;
import cn.four.hqServer.common.utils.RedisUtil;
import cn.four.hqServer.modules.userlogin.dto.UserLoginDto;
import cn.four.hqServer.modules.userlogin.dto.UserNumDto;
import cn.four.hqServer.modules.userlogin.service.ZxUserLoginService;
import cn.four.hqServer.modules.userlogin.utils.GetCaptcha;
import cn.four.hqServer.modules.userlogin.utils.SessionContext;
import cn.four.hqServer.modules.userlogin.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Api(tags = "用户登录")
@RestController
public class ZxUserLoginController {
    @Autowired
    private ZxUserLoginService zxUserLoginService;

    @PostMapping("/login")
    @CrossOrigin
    public Result<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto,HttpServletRequest request){
        UserLoginVo userLoginVo =zxUserLoginService.login(userLoginDto.getUserId(), userLoginDto.getPassword());
        //根据返回的状态码判断登录成功还是失败
        if (userLoginVo == null) {
            return Result.error();
        }
        request.getSession().setAttribute("userInfo",userLoginVo);
        return Result.success(userLoginVo);
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().removeAttribute("userInfo");
        if(request.getSession().getAttribute("userInfo")==null) {
            return Result.success("退出登录");
        }
        else return Result.error();
    }

    @PostMapping("/getCaptcha1")
    public Result getCaptcha1(@RequestBody HqUserInfo userInfo, HttpServletResponse response, HttpServletRequest request) {
        Result result = null;
        //判断电话号码是否注册
        if (zxUserLoginService.selectUsernameByNumber(userInfo.getNumber())) {
            //网上找的短信发送的接口向电话号码发送验证码，目前只能发送到一个固定的手机号
            String captcha = GetCaptcha.message(userInfo.getNumber());

            //获取存储session的对象
            SessionContext sessionContext = SessionContext.getSessionContext();
            //获取session
            HttpSession session = request.getSession();
            //向session中添加数据
            session.setAttribute(userInfo.getNumber(), captcha);
            session.setAttribute("userPhone", userInfo.getNumber());
            session.setMaxInactiveInterval(180);
            //存储session
            sessionContext.addSession(session);
            result.setCode(200);
            result.setMessage(session.getId());
        } else {
            result.setMessage("手机号未注册，请检查手机号码是否错误！");
            result.setCode(500);
        }
        return result;
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @ApiOperation(value = "获取验证码")
    @GetMapping("/getCaptcha/{phone}")
    public Result getCaptcha(@PathVariable String phone) {
        //判断电话号码是否注册
        if (zxUserLoginService.isLogin(phone)) {
            return Result.success();
        } else {
            return Result.error("手机号未注册");
        }
    }

    /**
     * 判断验证码
     * @param userNumDto
     * @return
     */
    @ApiOperation(value = "判断验证码")
    @PostMapping("/loginByPhone")
    public Result loginByPhone(@RequestBody UserNumDto userNumDto, HttpServletRequest request) {
        //判断验证码是否正确
        if (zxUserLoginService.loginByPhone(userNumDto)) {
            UserLoginVo userInfo = zxUserLoginService.getUserInfo(userNumDto.getPhone());
            request.getSession().setAttribute("userInfo",userInfo);
            return Result.success(userInfo);
        } else {
            return Result.error("验证码错误");
        }
    }


    @PostMapping("/loginByPhone1")
    public Result loginByPhone(@RequestBody Map<String, String> map, HttpServletResponse response) {
        Result result = null;
        result.setCode(500);
        //判断是否输入手机号和验证码
        if(map.get("captcha") == "" || map.get("userPhone") == ""){
            result.setMessage("请输入手机号码和验证码！");
            return result;

            //判断sessionId是否为空，为空则表示没发验证码
        } else if (map.get("sid") == "") {
            result.setMessage("请先获取验证码再登录！！");
            return result;
        }
        SessionContext sessionContext = SessionContext.getSessionContext();
        //根据sessionid获取session
        HttpSession session = sessionContext.getSession(map.get("sid"));

        try {
            if (map.get("userPhone").equals(session.getAttribute("userPhone")) && map.get("captcha").equals(session.getAttribute(map.get("userPhone")))) {
                //登录成功删除session
                session.invalidate();
                sessionContext.delSession(map.get("sid"));
                result.setCode(200);
                result.setMessage("登录成功！");
                return result;
            }
        }catch (IllegalStateException e){
            result.setMessage("验证码已失效！");
            return result;
        }
        result.setMessage("验证码错误！");
        return result;
    }

}


